package cn.caipengbo.androidapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private EditText editTextUrl;
    private EditText editTextResult;

    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextUrl = (EditText) findViewById(R.id.edit_url);
        editTextResult = (EditText) findViewById(R.id.edit_result);

        requestQueue = Volley.newRequestQueue(this);

    }
    public void testHttpUrlConnectionGet(View view) {
        final ProgressDialog progressDialog = ProgressDialog.show(this, null, "请求中...");
        new Thread() {
            public void run() {
                String path = editTextUrl.getText().toString();
                try {
                    URL url = new URL(path);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setReadTimeout(6000);
                    httpURLConnection.connect();

                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        final StringBuilder response = new StringBuilder();
                        String line;
                        while ((line =reader.readLine()) != null) {
                            response.append(line);
                        }
                        // 主线程更新UI
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                editTextResult.setText(response);
                                progressDialog.dismiss();
                            }
                        });
                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                    httpURLConnection.disconnect();
                } catch (Exception e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void testHttpUrlConnectionPost(View view) {

        final ProgressDialog progressDialog = ProgressDialog.show(this, null, "请求中...");
        // 注意要启动线程(start)
        new Thread() {
            public void run() {
                String path = editTextUrl.getText().toString();
                try {
                    URL url = new URL(path);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setReadTimeout(6000);
                    httpURLConnection.connect();

                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    String data = "name=Tom&age=33";
                    outputStream.write(data.getBytes("utf-8"));


                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        final StringBuilder response = new StringBuilder();
                        String line;
                        while ((line =reader.readLine()) != null) {
                            response.append(line);
                        }
                        // 主线程更新UI
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                editTextResult.setText(response);
                                progressDialog.dismiss();
                            }
                        });
                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                    httpURLConnection.disconnect();
                } catch (Exception e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void testVolleyGet(View view) {
        final ProgressDialog progressDialog = ProgressDialog.show(this, null, "使用Volley请求中...");
        String path = editTextUrl.getText().toString();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, path, new Response.Listener<String>(){
            @Override
            public void onResponse(String s) {
                editTextResult.setText(s);
                progressDialog.dismiss();
            }
        }, null);
        requestQueue.add(stringRequest);
    }

    public void testVolleyPost(View view) {
        final ProgressDialog progressDialog = ProgressDialog.show(this, null, "使用Volley请求中...");
        String path = editTextUrl.getText().toString();
        StringRequest stringRequest = new StringRequest(Request.Method.POST,path, new Response.Listener<String>(){
            @Override
            public void onResponse(String s) {
                editTextResult.setText(s);
                progressDialog.dismiss();
            }
        }, null) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("name", "蔡鹏博");
                map.put("age", "19");
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    public void toFragmentActivity(View view) {
        Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
        startActivity(intent);
    }
}
